package com.fengwk.cv4j.view.ind;

import org.nd4j.linalg.api.ndarray.INDArray;

import com.fengwk.cv4j.compute.Compute;
import com.fengwk.cv4j.factory.ViewFactory;
import com.fengwk.cv4j.view.View;
import com.fengwk.cv4j.view.common.MeanView;
import com.fengwk.support.exception.BaseException;

/**
 * 矩阵求均值
 * 
 * @author fengwk
 *
 */
public class INDMeanView extends MeanView<INDArrayWrap> {

	private static final long serialVersionUID = -2466071888885776603L;

	public INDMeanView(Compute<INDArrayWrap> compute, ViewFactory<INDArrayWrap> factory, @SuppressWarnings("unchecked") View<INDArrayWrap>...vs) {
		super(compute, factory, vs);
		checkVsMin(2, vs);
	}

	@Override
	public View<INDArrayWrap> gradient0(int idx) {
	    INDArrayWrap wrap0 = t(0);
        INDArray arr = wrap0.arr();
        float product = 1.0f;
        for (int i = 1; i < len(); i ++) {
            Number n = t(i).num();
            if (n == null)
                throw new BaseException("n == null");
            product *= arr.size(n.intValue());
        }
        if (arr == null) {
            return super.gradient0(idx);
        } else {
            if (idx == 0) 
                return f().of(1 / product, wrap0);
            if (idx < len())
                return f().of(0);
            throw new BaseException("idx >= len()");
        }
	}
	
}
